<template>
	<div>
		<el-button type="primary" plain @click="toBack">返回</el-button>
		<h3>出库详情</h3>
		<el-form inline label-position="top" :model="outbound" ref="ruleForm">
			<el-form-item label="申请类型">
				<el-select v-model="outbound.type" style="width: 100%;" :disabled="typeDisabled()">
					<el-option label="卖出商品" :value="0"></el-option>
					<el-option label="员工借出" :value="1"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="申请人" v-if="outbound.id !== null">
				<el-input :value="outbound.applicant" readonly>
				</el-input>
			</el-form-item>
			<el-form-item label="出库价格" v-if="userInfo.roleId === '1'">
				<el-input v-model="outbound.price" type="number" step="0.01" 
					@input="checkPrice" :readonly="readonly">
				</el-input>
			</el-form-item>
			<el-form-item label="备注">
				<el-input v-model="outbound.remark" placeholder="输入备注" 
					:autosize="{ minRows: 4, maxRows: 4}" type="textarea"
					:readonly="outbound.status === 4"
					@change="changeRemark">
				</el-input>
			</el-form-item>
			<el-form-item label="物流信息" v-if="outbound.returnId !== null">
				<div style="display: flex;">
					<div class="order-img-div" 
						v-for="(item,index) in logisticsInformationList"
						:key="index" style="position: relative;margin-right: 10px;">
						<el-image :src="READ_IMG_URL+item" class="htimg"
							:preview-src-list="addUrl(logisticsInformationList)">
						</el-image>
						<i class="el-icon-close hover-icon" @click="deleteImg(index)"></i>
					</div>
					<img :src="imgUrl" class="htimg" @click="selectFile"
						v-if="logisticsInformationList.length < 3"/>
				</div>
			</el-form-item>
			<el-form-item label="产品列表" style="width: 100%">
				<div>
					<el-button type="text" @click="devicesDialogShow" v-if="!readonly">
						添加产品
					</el-button>
				</div>
				<el-table :data="outbound.outboundPartList" border style="width: 100%" :max-height="400">
					<el-table-column prop="i" fixed="left" label="序号" width="50">
					</el-table-column>
					<el-table-column label="图片" width="115">
						<template slot-scope="scope">
							<el-image :src="READ_IMG_URL+scope.row.image" 
								style="width: 90px; height: 90px;"
								:preview-src-list="new Array(READ_IMG_URL+scope.row.image)">
							</el-image>
						</template>
					</el-table-column>
					<el-table-column prop="isProduct" label="产品类型" width="80">
						<template slot-scope="scope">
							<el-tag v-if="scope.row.isProduct === 0">成品</el-tag>
							<el-tag type="warning" v-if="scope.row.isProduct ===1">零件</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="partName" label="产品名称" fit>
					</el-table-column>
					<el-table-column prop="model" label="产品型号" fit>
					</el-table-column>
					<el-table-column prop="devicesDescribe" label="产品描述" fit>
					</el-table-column>
					<el-table-column prop="remark" label="备注" fit>
					</el-table-column>
					<el-table-column prop="price" label="销售单价" width="80"
						v-if="userInfo.roleId === '1'">
					</el-table-column>
					<el-table-column prop="outboundCount" label="出库数量" width="120">
						<template slot-scope="scope">
							<el-input v-model="scope.row.outboundCount" type="number" 
								placeholder="出库数量"
								@input="inputCheck($event,scope.row)" 
								@change="countChange($event,scope.row)"
								:readonly="readonly">
							</el-input>
							<span v-if="scope.row.inventory" style="color: red;">
								库存不足
							</span>
						</template>
					</el-table-column>
					<el-table-column prop="totalPrice" label="总计" width="80"
						v-if="userInfo.roleId === '1'">
					</el-table-column>
					<el-table-column label="操作" width="70" v-if="!readonly">
						<template slot-scope="scope">
							<el-button type="text" @click="deleteParts(scope.row)">
								删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-form-item>
			<el-form-item v-if="!readonly" style="width: 100%;">
				<el-button @click="reset">重置</el-button>
				<el-button type="primary" @click="onSubmit">
					申请
				</el-button>
			</el-form-item>
		</el-form>

		<!-- 选择产品 -->
		<el-dialog style="margin-top:0" :visible.sync="devicesShow" width="80%" title="选择产品">
			<div style="display: flex;justify-content: space-between;margin-bottom: 10px;">
				<div>
					<el-button type="primary" @click="confirmParts">确定</el-button>
				</div>
				<!-- 条件查询 -->
				<div style="display: flex;">
					<el-input v-model="form.partName" placeholder="按名称型号搜索" clearable @change="getDevicesList">
					</el-input>
					<el-select v-model="form.isProduct" @change="getDevicesList"
						style="width: 120px; margin-left: 10px">
						<el-option label="零件" :value="1"></el-option>
						<el-option label="成品" :value="0"></el-option>
					</el-select>
				</div>
			</div>
			<el-table :data="devicesList" v-loading="loading" border style="width: 100%" :max-height="430"
				:row-key="(row) => row.id" @selection-change="handleSelectionChange" ref="multipleTable">
				<el-table-column type="selection" :reserve-selection="true" width="40">
				</el-table-column>
				<el-table-column prop="i" label="序号" width="60">
				</el-table-column>
				<el-table-column label="产品图片" width="115">
					<template slot-scope="item">
						<el-image style="width: 90px; height: 90px" 
							:src="READ_IMG_URL+item.row.image"
							:preview-src-list="new Array(READ_IMG_URL+item.row.image)">
						</el-image>
					</template>
				</el-table-column>
				<el-table-column prop="isProduct" label="产品类型" width="80">
					<template slot-scope="scope">
						<el-tag v-if="scope.row.isProduct === 0">成品</el-tag>
						<el-tag type="warning" v-if="scope.row.isProduct ===1">零件</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="partName" label="产品名称" fit>
				</el-table-column>
				<el-table-column prop="model" label="产品型号" fit>
				</el-table-column>
				<el-table-column prop="devicesDescribe" label="产品描述" fit>
				</el-table-column>
				<el-table-column prop="remark" label="备注" fit>
				</el-table-column>
				<el-table-column prop="price" label="销售价格" width="80"
					v-if="userInfo.roleId === '1'">
				</el-table-column>
				<el-table-column prop="count" label="库存数量" width="80">
				</el-table-column>
			</el-table>
			<el-pagination background :current-page="form.currentPage" :page-size="form.pageSize" :total="form.total"
				:page-sizes="[20, 50, 100]" @size-change="formSizeChange" @current-change="formCurrentChange"
				layout="total, sizes, prev, pager, next, jumper">
			</el-pagination>
		</el-dialog>
		<input type="file" id="fileInput" ref="fileInput" style="display: none" @change="handleFileChange" />
	</div>
</template>

<script>
	import warehouseApi from '../../../api/warehouse';
	import orderApi from '../../../api/order.js';
	import uploadFile from '../../../api/uploadFile.js'
	import config from '../../../api/apiURL.js';
	export default {
		data() {
			return {
				READ_IMG_URL: config.READ_IMG_URL,
				userInfo: {},
				readonly: true,
				outbound: {
					id: null,
					returnId: null, // 订单id
					userId: null, // 申请人id
					applicant: null, // 申请人姓名
					managementId: null, // 审核人id
					managementName: null, // 审核人姓名
					outboundTime: null, // 审核时间
					price: 0.00, // 出库价格
					status: 1, // 待审核
					type: 1, // 0卖出商品，1员工借出
					remark: null, // 备注
					createTime: null, // 申请时间
					outboundPartList: []
				},
				imgUrl: '',
				selectedFile: '',
				logisticsInformationList: [],
				loading: false,
				devicesShow: false, // 控制选择产品弹窗显示
				form: {
					partName: null,
					isProduct: 0,
					currentPage: 1,
					pageSize: 50,
					total: 0,
				},
				devicesList: [], // 产品列表
				selectDevicesList: [], // 选择的产品列表
			}
		},
		created() {
			this.userInfo = JSON.parse(localStorage.getItem("userInfo"))
			const id = localStorage.getItem("outboundId");
			this.imgUrl = "https://kris-k.oss-cn-hangzhou.aliyuncs.com/kris/c179093a-41b0-4c70-bc1f-6e5973f35c98-jia.png";
			if (id) {
				this.outbound.id = id
				this.getDevicesOutbound();
			}else {
				this.readonly = false;
			}
		},
		destroyed() {
			localStorage.removeItem("outboundId");
		},
		methods: {
			// 返回上个页面
			toBack() {
				this.$router.push({
					path: "/warehouse/outbound/outbound"
				})
			},
			// 获取出库信息
			getDevicesOutbound() {
				const loading = this.$loading({
					lock: true,
					text: 'Loading...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				const data = {
					id: this.outbound.id
				}
				warehouseApi.getDevicesOutbound(data).then(res => {
					if (res.code === 200) {
						this.outbound = res.data;
						if (this.outbound.logisticsInformationList !== null){
							this.logisticsInformationList = this.outbound.logisticsInformationList;
						}
						this.outbound.outboundPartList = res.data.outboundPartList.map((item, index) => {
							let data = {
								i: index+1,
								partId: item.partId,
								image: item.image,
								partName: item.partName,
								isProduct: item.isProduct,
								model: item.model,
								price: item.price, // 销售单价
								outboundCount: item.outboundCount, // 出库数量
								totalPrice: item.price, // 总计金额
								count: item.count, // 库存
								devicesDescribe: item.devicesDescribe,
								remark: item.remark,
								inventory: false, // 库存不足
							}
							return data;
						})
						if (this.outbound.status === 1 || this.outbound.status === 2){
							this.readonly = false;
						}
					}
				}).finally(() => {
					loading.close();
				})
			},
			// 是否禁用产品选择弹窗
			devicesDialogDisabled() {
				if (this.outbound.status === 0) {
					return true;
				} else if (this.outbound.id !== null || this.outbound.type === 0) {
					return true;
				}
				return false;
			},
			// 打开选择产品弹窗
			devicesDialogShow() {
				this.devicesShow = true;
				this.getDevicesList();
			},
			// 获取产品列表
			getDevicesList() {
				this.loading = true;
				warehouseApi.getDeviceList(this.form).then(res => {
					if (res.code === 200) {
						this.form.total = res.data.total
						this.devicesList = res.data.devicesList.map((item, index) => {
							item.i = (this.form.currentPage - 1) * this.form.pageSize + index + 1;
							return item;
						})
						// 显示已选择的
						this.$refs.multipleTable.clearSelection();
						if (this.outbound.outboundPartList.length > 0) {
							this.devicesList.forEach(row => {
								this.outbound.outboundPartList.forEach(part => {
									if (part.partId === row.id) {
										this.$refs.multipleTable.toggleRowSelection(row, true);
									}
								})
							})
						}
					}
				}).finally(() => {
					this.loading = false;
				})
			},
			// 页码变化
			formCurrentChange(currentPage) {
				this.form.currentPage = currentPage;
				this.getDevicesList();
			},
			// 页码条数变化
			formSizeChange(pageSize) {
				this.form.pageSize = pageSize;
				this.getDevicesList();
			},
			// 多选产品
			handleSelectionChange(e) {
				this.selectDevicesList = e;
			},
			// 确认选择
			confirmParts() {
				for (var i = 0; i < this.selectDevicesList.length; i++) {
					var devices = this.selectDevicesList[i];
					if (this.outbound.outboundPartList.length > 0) {
						let flog = false;
						for (var j = 0; j < this.outbound.outboundPartList.length; j++) {
							var part = this.outbound.outboundPartList[j];
							if (part.partId === devices.id) {
								flog = true;
								break;
							}
						}
						if (flog) {
							continue;
						}
					}
					let data = {
						partId: devices.id,
						image: devices.image,
						partName: devices.partName,
						isProduct: devices.isProduct,
						model: devices.model,
						price: devices.price, // 销售单价
						outboundCount: 1, // 出库数量
						totalPrice: devices.price, // 总计金额
						count: devices.count, // 库存
						devicesDescribe: devices.devicesDescribe,
						remark: devices.remark,
						inventory: false, // 库存不足
					}
					this.outbound.outboundPartList.push(data);
					this.computeAmount();
				}
				let newList = this.outbound.outboundPartList.map((item, index) => {
					item.i = index + 1;
					return item;
				})
				this.outbound.outboundPartList = newList;
				this.devicesShow = false;
			},
			// 删除产品
			deleteParts(item) {
				let newList = this.outbound.outboundPartList.filter(part => part.partId !== item.partId)
				this.outbound.outboundPartList = newList.map((part, index) => {
					part.i = index + 1;
					return part;
				})
				if (this.$refs.multipleTable !== null) {
					this.devicesList.forEach(row => {
						if (item.partId === row.id) {
							this.$refs.multipleTable.toggleRowSelection(row, false);
						}
					})
				}
				this.computeAmount();
			},
			// 类型是否禁用
			typeDisabled() {
				if (this.userInfo.roleId === "1" && 
					(this.outbound.status === 1 || this.outbound.status === 2) ) {
					return false;
				}
				return true;
			},
			// 数量输入检查，计算库存
			inputCheck(e, row) {
				let inputNumber = row.outboundCount
				if (inputNumber <= 0) {
					inputNumber = 1
				}
				// 只能输入整数
				let regex = /\./;
				if (regex.test(inputNumber)) {
					// 带小数设置为1
					inputNumber = 1
				}
				let value = parseInt(inputNumber)
				if (isNaN(value)) {
					value = 1;
				}

				// 计算库存
				if (row.count - row.outboundCount < 0) {
					row.inventory = true;
				} else {
					row.inventory = false;
				}
				row.outboundCount = value
			},
			// 计算单个产品总计
			countChange(e, row) {
				row.totalPrice = parseFloat((row.outboundCount * row.price).toFixed(2))
				this.computeAmount();
			},
			// 检查数字，小于0.00，或者超过小数点后两位返回0
			checkNumber(value) {
				if (value < 0.00) {
					value = 0;
				}
				// 使用正则表达式匹配小数点后两位以内的数字或整数
				let regex = /^\d+(\.\d{1,2})?$/;
				if (!regex.test(value)) {
					value = 0
				}
				return value;
			},
			// 检查输入的金额
			checkPrice() {
				let inputNumber = parseFloat(this.outbound.price);
				inputNumber = this.checkNumber(inputNumber);
				this.outbound.price = inputNumber
			},
			// 计算总金额
			computeAmount() {
				if (this.outbound.outboundPartList.length > 0) {
					let Amount = 0.00
					if (this.outbound.type === 0){
						this.outbound.outboundPartList.forEach(item => {
							Amount = Amount + item.totalPrice
						})
					}
					this.outbound.price = Amount;
				}
			},
			// 点击上传图片
			selectFile() {
				this.$refs.fileInput.click();
			},
			// 上传oos
			handleFileChange(event) {
				this.selectedFile = event.target.files[0];
				// 上传前验证
				const fileSuffix = this.selectedFile.name.substring(this.selectedFile.name.lastIndexOf(".") + 1);
				const whiteList = ["jpg", "jpeg", "png", "JPG", "JPEG", "PNG"];
				if (whiteList.indexOf(fileSuffix) === -1) {
					this.$message.error("上传文件只能是 jpg、png格式！");
					return;
				}
				const isLt5M = this.selectedFile.size / 1024 / 1024 < 5;
				if (!isLt5M) {
					this.$message.error('上传的图片大小不能超过5MB!');
					return;
				}
				this.uploadImage();
			},
			//发送上传文件api
			uploadImage() {
				const loading = this.$loading({
					lock: true,
					text: '上传中...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				let formData = new FormData();
				formData.append("file", this.selectedFile);
				uploadFile.uploadImage(formData).then(res =>{
					if (res.code === 200){
						const url = res.data
						this.logisticsInformationList.push(url);
						if (this.outbound.returnId !== null) {
							const data = {
								id: this.outbound.returnId,
								logisticsInformation: this.logisticsInformationList.join(";")
							}
							orderApi.orderDelivery(data).then(res => {
								if (res.code === 200) {
									this.$message.success("上传成功")
								}
							}).finally(() =>{
								loading.close();
							});
						}
					}
				}).finally(() =>{
					this.selectedFile = '';
					loading.close();
				})
				// UploadFile(formData).then((data) => {
				// 	let url = data.data;
				// 	this.logisticsInformationList.push(url);
				// 	if (this.outbound.returnId !== null) {
				// 		const data = {
				// 			id: this.outbound.returnId,
				// 			logisticsInformation: this.logisticsInformationList.join(";")
				// 		}
				// 		orderApi.orderDelivery(data).then(res => {
				// 			if (res.code === 200) {
				// 				this.$message.success("上传成功")
				// 			}
				// 		}).finally(() =>{
				// 			loading.close();
				// 		});
				// 	}
				// }).catch(() =>{
				// 	this.$message.success("上传失败");
				// 	loading.close();
				// });
			},
			// 删除图片
			deleteImg(index){
				this.$confirm('是否要删除此图片？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					// 用户点击了确定按钮时执行的操作
					this.logisticsInformationList.splice(index,1);
					let logisticsInformation = '';
					if (this.logisticsInformationList.length >0){
						logisticsInformation = this.logisticsInformationList.join(";")
					}
					const data = {
						id: this.outbound.returnId,
						logisticsInformation: logisticsInformation
					}
					const loading = this.$loading({
						lock: true,
						text: '请求中...',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.7)'
					});
					orderApi.orderDelivery(data).then(res => {
						if (res.code === 200) {
							this.$message.success("删除成功")
						}
					}).finally(() =>{
						loading.close();
					})
				}).catch(() => {
					// 用户点击了取消按钮时执行的操作，或者点击遮罩层关闭对话框时触发的事件
				});
			},
			// 提交
			onSubmit() {
				if (this.outbound.outboundPartList.length < 1) {
					this.$message.error("请选择产品！")
					return;
				}
				if (this.outbound.id == null) {
					// 新增
					warehouseApi.addDevicesOutbound(this.outbound).then(res => {
						if (res.code === 200) {
							this.$message.success("提交成功")
							this.reset();
						}
					})
				} else {
					// 修改
					warehouseApi.updateDevicesOutbound(this.outbound).then(res => {
						if (res.code === 200) {
							this.$message.success("提交成功")
							this.getDevicesOutbound();
						}
					})
				}
			},
			// 重置
			reset() {
				this.outbound.price = 0.00;
				this.outbound.remark = null;
				this.outbound.outboundPartList = [];
				if(this.$refs.multipleTable){
					this.$refs.multipleTable.clearSelection();
				}
			},
			changeRemark(e){
				if (this.outbound.id !== null){
					this.$confirm("是否要修改备注？", "提示", {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						const data = {
							id: this.outbound.id,
							remark: e
						}
						warehouseApi.updateDevicesOutbound(data).then(res => {
							if (res.code === 200) {
								this.$message.success("修改成功")
								this.getDevicesOutbound();
							}
						})
					}).catch(() =>{
						console.log("取消")
						this.outbound.remark = null;
					})
				}
			},
			addUrl(list){
				let newList = [];
				list.forEach(item =>{
					newList.push(this.READ_IMG_URL+item);
				})
				return newList;
			}
		}
	}
</script>

<style>
	.el-form-item {
		width: 520px;
	}
	
	.htimg {
		width: 150px;
		height: 150px;
		object-fit: cover;
		/* 保持原始宽高比，填充容器 */
	}
	
	.order-img-div{
		width: 150px;
		height: 150px;
	}
	
	.order-img-div:hover .hover-icon{
		display: block;
	}
	
	.hover-icon{
		display: none;
		font-size: 24px;
		position: absolute;
		top: 0; 
		right: 0;
		color: #ffffff;
		background-color: black;
		opacity: 0.9
	}
	
	.hover-icon:hover{
		cursor: pointer;
	}
</style>